const axios = require('axios');
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const urlPrefix = "https://cn.bing.com"
const imageMsg = "Load Image Phase => "
var fs = require("fs")
var sd = require('silly-datetime');
var bgName = "bg"+sd.format(new Date(), 'YYYYMMDD')+".jpg";
var pathTo = "public/img/"+bgName

var loadImage = function() {

axios.get(urlPrefix)
  .then(res => {
    return new Promise( resolve => {resolve(res.data)});
  })
  .then(page =>{
      let htmlPage = new JSDOM(page)
      let link = htmlPage.window.document.getElementById("bgLink")
      return axios({method: "get", url: urlPrefix+link.href, responseType: 'stream'})

  })
  .then(response => {
    return new Promise((resolve) => {
        response.data.pipe(fs.createWriteStream(pathTo));
        resolve("OK")
    })
  })
  .then(result => {
      console.log(imageMsg+result)
  })
  .catch(err => {
    console.log(imageMsg+err);
  });

}

setInterval(loadImage, 24*60*60*1000)

module.exports = {
  loadImage,
}
